<?php

/**
 * Faz a consulta no banco e retornar o json
 *
 * @param String $campos
 * @param String $from
 * @param String $where
 * @param String $final
 * @param String $actions
 * @param String $page
 * @param String $primaryKey
 * @return string
 */
function sqlGrid($idGrid, $campos, $from, $arrWhere, $final, $actions, $page, $primaryKey) {
    $total = 0;
    $param = array();
    $count = count($arrWhere);

    if ($count > 0) {
        $where = stripslashes($arrWhere[0]);
        if ($count > 1) {
            $param = $arrWhere;
            array_shift($param);
        }
    }

    $sqlCount = 'SELECT count(*) FROM ' . $from . ' ' . $where;
//    echo $sqlCount, '<br><br>';
    try {
        $db1 = new GDbMysql();
        empty($param) ? $db1->execute($sqlCount) : $db1->execute($sqlCount, $param);

        $db1->fetch();
        $total = $db1->res[0];
        $db1->close();

        $sqlGrid = "SELECT $campos FROM $from $where $final";
//        echo $sqlGrid, '<br><br>';
        try {
            $db2 = new GDbMysql();
            empty($param) ? $db2->execute($sqlGrid) : $db2->execute($sqlGrid, $param);

            $linha = 0;
            $arrayRows = array();

            while ($db2->fetch()) {
                $numFields = $db2->fieldCount();
                $indices = array();
                $lin = 0;
                foreach ($db2->res as $indice => $valor) {
                    if (!is_numeric($indice))
                        $arrayRows[$linha][$indice] = $db2->res[$indice];
                }

                $linha++;
            }

            $json = array();
            $json['page'] = $page;
            $json['total'] = $total;
            $json['rows'] = makeRows($idGrid, $arrayRows, $actions, $primaryKey);

            return json_encode($json);
        } catch (GDbException $exc) {
            echo $exc->getTraceAsString();
        }
    } catch (GDbException $exc) {
        echo $exc->getTraceAsString();
    }
}

/**
 * Montar as linhas que serão inseridas na tabela do flexigrid
 *
 * @param String $arrayRows
 * @param String $actions
 * @param String $primaryKey
 * @return string
 */
function makeRows($idGrid, $arrayRows, $actions, $primaryKey) {
    $rows = array();
    $rc = false;
    $i = 0;

    foreach ($arrayRows as $coluna) {
        $arrayKeys = explode(',', $primaryKey);
        $rel = "";
        $id = "";
        foreach ($arrayKeys as $value) {
            if ($rel != "") {
                $rel .= "," . $coluna[$value];
                $id .= "_" . str_replace(" ", "_", $coluna[$value]);
            } else {
                $rel .= $coluna[$value];
                $id .= str_replace(" ", "_", $coluna[$value]);
            }
        }

        $rows[$i]['id'] = $rel;
        $rows[$i]['cell'] = array();

        $j = 0;
        $rows[$i]['cell'][$j] = '<input type="checkbox" class="__checkbox" onClick="__acaoSelecao(\'' . $idGrid . '\',\'' . $rel . '\')" value="' . $rel . '" />';

        foreach ($coluna as $value) {
            $j++;
            $str = GF::formatTextToGrid($value);
            if (strlen($value) > 100) {
                $str = substr($str, 0, 100) . '...';
            }
            $rows[$i]['cell'][$j] = $str;
        }

        $colActions = "";
        $arrayActions = explode(',', $actions);

        $colActions .= '<ul class="__acoes">';

        foreach ($arrayActions as $acao) {
            $arrAcao = explode(':', $acao);
            $acao = $arrAcao[0];
            $titulo = ($arrAcao[1] == '') ? $acao : $arrAcao[1];
            if ($acao != 'inserir')
                $colActions .= '<li><a id="' . $acao . '_' . $id . '" class="__' . $acao . '" onClick="__' . $acao . '(\'' . $idGrid . '\',\'' . $rel . '\')" alt="' . $titulo . '" title="' . $titulo . '"></a></li>';
        }

        $colActions .= '</ul>';

        $j++;
        $rows[$i]['cell'][$j] = $colActions;

        $i++;
    }

    return $rows;
}

/**
 * Montar a clausula where
 *
 * @param String $qtype
 * @param String $query
 * @param String $comp Complemento
 * @return string
 */
function makeWhere($qtype, $query, $comp = '') {
    $where = '';
    $indices = '';
    $valores = array();
    if ($query) {
        $campos = explode(";", $qtype);

        for ($i = 0; $i < count($campos); $i++) {
            $array = explode(":", $campos[$i]);
            if ($i == 0)
                $where .= " WHERE ($array[0] LIKE ? ";
            else
                $where .= " OR $array[0] LIKE ? ";

            $indices .= 's';
            $valores[] = "%$query%";
        }
        $where .= ") ";

        $arrWhere = array($where, $indices);
        $arrWhere = array_merge($arrWhere, $valores);
    }
    if ($comp) {
        if ($where == '')
            $compWhere = " WHERE " . $comp . " ";
        else
            $compWhere = " AND " . $comp . " ";

        $arrWhere[0] .= $compWhere;
    }

    return $arrWhere;
}

?>